package com.eet.elasticsearch.service.impl;

import com.eet.elasticsearch.constants.CommonConstants;
import com.eet.elasticsearch.model.Role;
import com.eet.elasticsearch.model.User;
import com.eet.elasticsearch.model.UserSearchParam;
import com.eet.elasticsearch.repository.ElasticOperationRepository;
import com.eet.elasticsearch.service.StandardService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 用户服务实现类
 *
 * @author Administrator
 */
@Service
public class UserServiceImpl implements StandardService, InitializingBean {
    @Autowired
    private ElasticOperationRepository operationRepository;

    private final String INDEX = CommonConstants.INDEX;

    private final String TYPE = CommonConstants.TYPE;

    @Override
    public void afterPropertiesSet() {
        operationRepository.createIndexIfNotExist(INDEX, TYPE);
    }

    /**
     * 批量添加用户
     *
     * @param users 用户信息集合
     */
    public void batchAddUser(List<User> users) {
        if (CollectionUtils.isEmpty(users)) {
            return;
        }
        for (User user : users) {
            operationRepository.addDocumentBulkProcess(INDEX, TYPE, user);
        }
    }

    @Override
    public void addUser(User user) {
        operationRepository.addDocument(INDEX, TYPE, user);
    }

    @Override
    public void deletedUserById(String id) {
        operationRepository.deleteDocumentById(INDEX, TYPE, id);
    }

    @Override
    public void updateUser(User user) {
        String userId = user.getId();
        user.setId(null);
        operationRepository.updateDocument(INDEX, TYPE, userId, user);
    }

    @Override
    public List<User> queryByUserName(String userName) {
        UserSearchParam searchParam = new UserSearchParam();
        searchParam.setUserName(userName);
        return operationRepository.queryDocumentByParam(INDEX, TYPE, searchParam, User.class);
    }

    @Override
    public List<User> queryByRoleName(Role role) {
        UserSearchParam param = new UserSearchParam();
        param.setRoleName(role.getName());
        return operationRepository.queryDocumentByParam(INDEX, TYPE, param, User.class);
    }
}
